package cn.devcat.sso.service.impl;

import cn.devcat.sso.config.exception.DevcatAuthException;
import cn.devcat.sso.entity.DevcatMenu;
import cn.devcat.sso.entity.DevcatRole;
import cn.devcat.sso.entity.PageData;
import cn.devcat.sso.entity.SearchCommonParam;
import cn.devcat.sso.mapper.DevcatMenuMapper;
import cn.devcat.sso.service.IDevcatMenuService;
import cn.devcat.sso.service.IDevcatRoleService;
import cn.devcat.sso.util.MenuTreeBuild;
import cn.devcat.sso.util.PageHelperUtil;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DevcatMenuServiceImpl extends ServiceImpl<DevcatMenuMapper, DevcatMenu> implements IDevcatMenuService {

  @Autowired
  IDevcatRoleService roleService;

  @Autowired
  UserUtil userUtil;

  @Override
  public void addMenu(DevcatMenu menu) {
    menu.setCreateTime(LocalDateTime.now());
    long count = count();
    menu.setMenuSort((int) count);
    if (menu.getRoleList() == null || menu.getRoleList().isEmpty()) {
      throw new RuntimeException("请至少选择一个角色");
    }
    String roleStr = StringUtils.join(menu.getRoleList(), ",");
    menu.setMenuRole(roleStr);
    if (StringUtils.isEmpty(menu.getParentId())) {
      menu.setParentId("0");
    }
    save(menu);
  }

  @Override
  public void delMenu(List<String> ids) {
    removeByIds(ids);
  }

  @Override
  public void setMenu(DevcatMenu menu) {
    updateById(menu);
  }

  @Override
  public List<DevcatMenu> menuTree() {
    List<DevcatRole> roleList = new ArrayList<>();
    try {
      String userId = userUtil.getUserByRequest().getId();
      roleList = roleService.getRoleListByUserId(userId);
    } catch (DevcatAuthException e) {
      DevcatRole one = roleService.getOne(new QueryWrapper<DevcatRole>().eq("role_code", "ROLE_ANONYMOUS"));
      roleList.add(one);
    }
    List<String> codeList = roleList.stream().map(DevcatRole::getRoleCode).collect(Collectors.toList());
    List<DevcatMenu> list = list();
    List<DevcatMenu> collect = list.stream().filter(item -> {
      String[] currentRoleList = item.getMenuRole().split(",");
      for (String s : currentRoleList) {
        if (codeList.contains(s)) {
          return true;
        }
      }
      return false;
    }).collect(Collectors.toList());
    return new MenuTreeBuild(collect).buildTree();
  }

  @Override
  public PageData<DevcatMenu> menuList(SearchCommonParam param) {
    QueryWrapper<DevcatMenu> wrapper = new QueryWrapper<>();
    if (StringUtils.isNotEmpty(param.getKeyword())) {
      wrapper.like("menu_name", param.getKeyword()).or().like("menu_route", param.getKeyword());
    }
    wrapper.orderByDesc("create_time");
    PageHelperUtil.handle(param);
    List<DevcatMenu> list = list(wrapper);
    list.forEach(item -> item.setRoleList(Arrays.asList(item.getMenuRole().split(","))));
    return PageHelperUtil.makePageData(new PageInfo<>(list));
  }
}
